package com.fas.system.service.impl;

import com.fas.common.constant.Constants;
import com.fas.common.core.domain.entity.SysUser;
import com.fas.common.core.redis.RedisCache;
import com.fas.common.exception.ServiceException;
import com.fas.common.utils.DictUtils;
import com.fas.common.utils.StringUtils;
import com.fas.system.domain.FasWordOrder;
import com.fas.system.domain.FasWordOrderEngineer;
import com.fas.system.domain.vo.WordOrderAndEquipment;
import com.fas.system.domain.vo.WordOrderVo;
import com.fas.system.mapper.FasWordOrderEngineerMapper;
import com.fas.system.mapper.FasWordOrderMapper;
import com.fas.system.mapper.SysUserMapper;
import com.fas.system.service.IFasWordOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class FasWordOrderServiceImpl implements IFasWordOrderService {

    @Resource
    private FasWordOrderMapper fasWordOrderMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private FasWordOrderEngineerMapper fasWordOrderEngineerMapper;

    @Override
    public List<WordOrderVo> miniappIpqcCenterOrderList(Integer wordOrderStatus,Integer orderType,Integer userId) {
        return fasWordOrderMapper.miniappIpqcCenterOrderList(wordOrderStatus,orderType,userId);
    }

    @Override
    public int saveFasWordOrder(FasWordOrder fasWordOrder) {
        return fasWordOrderMapper.saveFasWordOrder(fasWordOrder);
    }

    @Override
    public int insertNullData(FasWordOrder fasWordOrder) {
        return fasWordOrderMapper.insertNullData(fasWordOrder);
    }

    /**
     * 进行中工单
     *
     * @return
     */
    @Override
    public List<WordOrderVo> miniappManorder(Long deptId,Integer cooperationCompanyId) {
        List<Integer> statusList = Arrays.asList(Constants.WORD_ORDER_STATUS_PROGRESSING,Constants.WORD_ORDER_STATUS_EVALUATING);
        return fasWordOrderMapper.miniappManorder(statusList,null,deptId,cooperationCompanyId);
    }

    @Override
    public Object miniappManorderDetail(Integer wordOrderId, Integer type) {
        // type : 0：巡检路线，2：报警路线
        if (type == 0) {
            return fasWordOrderMapper.findManLineDetail(wordOrderId);
        } else { // 报警路线
            WordOrderAndEquipment manAlarmDetail = fasWordOrderMapper.findManAlarmDetail(wordOrderId);
            if (manAlarmDetail != null && manAlarmDetail.getSystemId() != null){
                String value = DictUtils.getDictLabel("sys_equipment_system",manAlarmDetail.getSystemId());
                if (StringUtils.isNotBlank(value)){
                    manAlarmDetail.setSystemName(value);
                }

            }
            return manAlarmDetail;
        }
    }

    @Transactional
    @Override
    public int miniappManorderDetailResult(FasWordOrder fasWordOrder) {
        // 维保人员意见拒绝时，工单状态已完成
        if (!Objects.isNull(fasWordOrder.getManResult())) {
            fasWordOrder.setManSubmitDate(new Date());//维保单位提交时间
            if (fasWordOrder.getManResult() == 2 ) {//2：拒绝
                fasWordOrder.setWordOrderStatus(Constants.WORD_ORDER_STATUS_FINISH);
            } else if (fasWordOrder.getManResult() == 3 ) {// 3 ：维保单位自己处理
                fasWordOrder.setWordOrderStatus(Constants.WORD_ORDER_STATUS_FINISH);
            }else if (fasWordOrder.getManResult() == 1){
                fasWordOrder.setEngineerResult(3);//工程师正在接单状态
                // 判断工程师是否拒绝过这个工单，如果拒绝了这个工单则提醒维保单位选择其它工程师
                int exists = fasWordOrderEngineerMapper.judgeEngineerIsRefuse(fasWordOrder.getId(),fasWordOrder.getEngineerUserId());
                if (exists > 0)  throw new ServiceException("该工程师已拒绝此工单，请指派其他工程师");
            }
        } else if (!Objects.isNull(fasWordOrder.getEngineerGrade())) {//维修工程师给工程师等级评分
            fasWordOrder.setWordOrderStatus(Constants.WORD_ORDER_STATUS_FINISH);
        }
        return fasWordOrderMapper.updateFasWordOrder(fasWordOrder);
    }

    @Override
    public List<WordOrderVo> miniappEngineerOrder(Integer userId,String startTime,String endTime,Integer cooperationCompanyId,Integer engineerResult) {
        List<WordOrderVo> list = fasWordOrderMapper.miniappEngineerOrder(Constants.WORD_ORDER_STATUS_PROGRESSING, userId,startTime,endTime,cooperationCompanyId,null,3,null);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public Object miniappEngineerOrderDetail(Integer wordOrderId, Integer type) {
        if (type == 0) {
            return fasWordOrderMapper.findEngineerLineDetail(wordOrderId);
        } else { // 报警路线
            WordOrderAndEquipment engineerAlarmDetail = fasWordOrderMapper.findEngineerAlarmDetail(wordOrderId);
            if (engineerAlarmDetail != null && StringUtils.isNotBlank(engineerAlarmDetail.getSystemId()) ){
                engineerAlarmDetail.setSystemName(DictUtils.getDictLabel("sys_equipment_system",engineerAlarmDetail.getSystemId()));
            }
            if (engineerAlarmDetail != null && engineerAlarmDetail.getEngineerList() != null && engineerAlarmDetail.getEngineerList().size()>0){
                engineerAlarmDetail.setEngineerResult(2);
            }
            return engineerAlarmDetail;
        }
    }

    @Transactional
    @Override
    public int miniappEngineerOrderDetailResult(FasWordOrder fasWordOrder,Integer userId) {
        Date date = new Date();
        if (fasWordOrder.getEngineerResult() == null) { // 工程师提交维修报告
            fasWordOrder.setEngineerSubmitDate(date);//工程师提交时间
            fasWordOrder.setWordOrderStatus(Constants.WORD_ORDER_STATUS_EVALUATING);
        } else {
            fasWordOrder.setEngineerAcceptDate(date);
            if(fasWordOrder.getEngineerResult() == 2){//工程师拒绝
                FasWordOrderEngineer fasWordOrderEngineer = new FasWordOrderEngineer();
                fasWordOrderEngineer.setWordOrderId(fasWordOrder.getId());
                fasWordOrderEngineer.setEngineerUserId(userId);
                fasWordOrderEngineer.setEngineerRefuseReason(fasWordOrder.getEngineerRefuseReason());
                fasWordOrderEngineerMapper.insertFasWordOrderEngineer(fasWordOrderEngineer);
            }else{
                fasWordOrder.setEngineerResult(1);
            }
        }
        return fasWordOrderMapper.updateFasWordOrder(fasWordOrder);
    }

    @Override
    public List<SysUser> miniappEngineerList(String permanentResidence) {
        return sysUserMapper.selectEngineerList(permanentResidence);
    }

    @Override
    public List<WordOrderVo> miniappManCenterOrderList(Integer wordOrderStatus,Long deptId,Integer cooperationCompanyId) {
        List<Integer> integers = wordOrderStatus == null ? null: Collections.singletonList(wordOrderStatus);
        List<WordOrderVo> list = fasWordOrderMapper.miniappManorder(integers, null, deptId, cooperationCompanyId);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public List<WordOrderVo> miniappEngineerCenterOrderList(Integer wordOrderStatus,Integer userId,Integer engineerResult,Integer cooperationCompanyId,Integer status,Long deptId) {
        List<WordOrderVo> list = fasWordOrderMapper.miniappEngineerOrder(wordOrderStatus, userId, null, null, cooperationCompanyId, engineerResult, status,deptId);
        List<WordOrderVo> resultList = new ArrayList<>();
        // 工程师有拒绝理由的数据，将engineer字段设置为 已拒绝（2）
        for (WordOrderVo wordOrderVo : list) {
            if (wordOrderVo.getCooperationCompanyId() != null){
                wordOrderVo.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(wordOrderVo.getCooperationCompanyId()));
            }
            // 工程师拒绝的工单
            if (!CollectionUtils.isEmpty(wordOrderVo.getEngineerList())){
                wordOrderVo.setEngineerResult(2);
            }
            if (wordOrderStatus != null || engineerResult != null){
                if (wordOrderStatus != null && wordOrderVo.getEngineerResult() != null  && wordOrderVo.getEngineerResult() != 2){
                    resultList.add(wordOrderVo);
                }
                if (engineerResult != null && wordOrderVo.getEngineerResult() != null && wordOrderVo.getEngineerResult() == 2){
                    resultList.add(wordOrderVo);
                }
            }else{
                resultList.add(wordOrderVo);
            }

        }
        return resultList;
    }
}